package com.lczc.soa.controller;


import com.lczc.soa.domain.Announce;
import com.lczc.soa.domain.SearchAnnounceResponse;
import com.lczc.soa.service.AnnounceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/Announce")
public class AnnounceController {

    @Autowired
    private AnnounceService announceService;
    @RequestMapping("/toadd")
    public String addAnnouncePage(Model model){
            model.addAttribute("announce",new Announce());
            return "announce_add";
    }

    @RequestMapping("/add")
    public String addAnnounce(Announce announce, HttpServletRequest request){
//        System.out.println("Controller:" + area.getAreaName());
        announce.setAnnounceName(request.getAttribute("announceName").toString());
        announce.setAuthor(request.getAttribute("author").toString());
        announce.setContent(request.getAttribute("content").toString());
        int updated = announceService.saveAnnounce(announce);
        return "redirect:/Announce/list";
    }

    @RequestMapping("/list")
    public String AnnounceList(){
        return "announce_list";
    }

    @GetMapping("/api/search")
    @ResponseBody
    public SearchAnnounceResponse searchAnnounceResponse(@RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("pageSize") Integer pageSize){
        return announceService.findAllAnnounce(pageNum,pageSize);
    }

    @GetMapping("/api/searchLike")
    @ResponseBody
    public SearchAnnounceResponse searchAnnounceResponseLike(@RequestParam("keywords") String keywords,
                                                     @RequestParam("pageNum") Integer pageNum,
                                                     @RequestParam("pageSize") Integer pageSize){
        return announceService.findAnnounceLikeAnnounceName(keywords,pageNum,pageSize);
    }

    @DeleteMapping("/delete")
    @ResponseBody
    public Boolean deleteAnnounce(@RequestParam("id") String id){
        int deleted = announceService.deleteAnnounce(id);
        return deleted > 0;
    }

    @RequestMapping("/show")
    public String AnnouncePage(Model model) {
        List<Announce> announces = announceService.listAnnounce();
        model.addAttribute("announces", announces);
        return "announce_show";
    }

    @RequestMapping("/all")
    public String AnnounceContent(@RequestParam("id") String id,Model model){
        Announce announce = announceService.findAnnounceByPrimaryKey(id);
        model.addAttribute("announce",announce);
        return "announce_all";
    }
}
